# -*- coding:utf-8 -*-
from framework.interface.abstract_api import AbstractApi
from marshmallow import Schema, fields, validate
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from collections import namedtuple
import requests
import os
import re
import random

class GetPic(AbstractApi):
    """
    接口：GetPic
    文件名输入：get_pic
    该接口访问地址为：http://10.10.30.247:9091/v1/get-pic
    输入：
    功能：
    输出：
    """

    class GetSchema(Schema):
        keyword = fields.Str(required=True)

    def handle_get_request(self):
        try:
            output1 = self.get_online_data()
            return output1
        except Exception as e:
            return f"程序异常: {str(e)}", 500

    # 业务1 获取图片
    def get_online_data(self):
        print("测试")
        keyword = self.get_param("keyword")
        print(keyword)
        save_dir = f"./static/{keyword}"
        page_num = 1
        status = self.get_images_from_baidu(keyword, page_num, save_dir)
        number = random.randint(0,8)
        data = {
            "status": status,
            "result_url": f"http://106.53.97.117:7777/static/{keyword}/00000{number}.jpg"
        }
        return data

    def get_images_from_baidu(self, keyword, page_num, save_dir):
        # UA 伪装：当前爬取信息伪装成浏览器
        # 将 User-Agent 封装到一个字典中
        # 【（网页右键 → 审查元素）或者 F12】 → 【Network】 → 【Ctrl+R】 → 左边选一项，右边在 【Response Hearders】 里查找
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
        # 请求的 url
        url = 'https://image.baidu.com/search/acjson?'
        n = 0
        for pn in range(0, 30 * page_num, 30):
            # 请求参数
            param = {'tn': 'resultjson_com',
                     # 'logid': '7603311155072595725',
                     'ipn': 'rj',
                     'ct': 201326592,
                     'is': '',
                     'fp': 'result',
                     'queryWord': keyword,
                     'cl': 2,
                     'lm': -1,
                     'ie': 'utf-8',
                     'oe': 'utf-8',
                     'adpicid': '',
                     'st': -1,
                     'z': '',
                     'ic': '',
                     'hd': '',
                     'latest': '',
                     'copyright': '',
                     'word': keyword,
                     's': '',
                     'se': '',
                     'tab': '',
                     'width': '',
                     'height': '',
                     'face': 0,
                     'istype': 2,
                     'qc': '',
                     'nc': '1',
                     'fr': '',
                     'expermode': '',
                     'force': '',
                     'cg': '',  # 这个参数没公开，但是不可少
                     'pn': pn,  # 显示：30-60-90
                     'rn': '30',  # 每页显示 30 条
                     'gsm': '1e',
                     '1618827096642': ''
                     }
            request = requests.get(url=url, headers=header, params=param)
            if request.status_code == 200:
                print('Request success.')
            request.encoding = 'utf-8'
            # 正则方式提取图片链接
            html = request.text
            image_url_list = re.findall('"thumbURL":"(.*?)",', html, re.S)
            print(image_url_list)

            if not os.path.exists(save_dir):
                os.makedirs(save_dir)

            for image_url in image_url_list:
                image_data = requests.get(url=image_url, headers=header).content
                with open(os.path.join(save_dir, f'{n:06d}.jpg'), 'wb') as fp:
                    fp.write(image_data)
                n = n + 1
        if n > 0:
            return 200
        else:
            return 405


